import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/controller/register.dart';
import 'package:ichinesereader/widgets/dialogs/accountSuccessDialogdart.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/utils/log.dart';

//直接使用webview的方式个人续订
// ignore: must_be_immutable
class PaymentFoWebWebview extends StatefulWidget {
  PaymentFoWebWebview({
    Key? key,
    this.from,
  }) : super(key: key);
  String? from;
  @override
  _PaymentFoWebWebviewState createState() => new _PaymentFoWebWebviewState();
}

class _PaymentFoWebWebviewState extends State<PaymentFoWebWebview> {
  final GlobalKey webViewKey = GlobalKey();
  RegisterController _registerController = Get.put(RegisterController());
  InAppWebViewController? webViewController;
  InAppWebViewSettings options = InAppWebViewSettings(
      useShouldOverrideUrlLoading: true,
      mediaPlaybackRequiresUserGesture: false,
      useHybridComposition: true,
      allowsInlineMediaPlayback: true,
      allowFileAccessFromFileURLs: true,
      allowUniversalAccessFromFileURLs: true,
      cacheEnabled: true,
      javaScriptEnabled: true,
      domStorageEnabled: true,
      allowsPictureInPictureMediaPlayback: true,
      enableViewportScale: true,
      disableLongPressContextMenuOnLinks: true,
      mixedContentMode: MixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW);

  late PullToRefreshController pullToRefreshController;
  late ContextMenu contextMenu;
  String url = "";
  double progress = 0;
  final urlController = TextEditingController();
  final box = Hive.box('appconfig');

  CookieManager cookieManager = CookieManager.instance();
  final expiresDate =
      DateTime.now().add(Duration(days: 3)).millisecondsSinceEpoch;
  // void loadautoken() async {
  //   await cookieManager.setCookie(
  //     url: WebUri.uri(Uri.parse(Constants.BaseURL)),
  //     name: "clientToken",
  //     value: _registerController.getToken,
  //     domain: Constants.BaseDomain,
  //     path: '/',
  //     expiresDate: expiresDate,
  //     isSecure: true,
  //   );

  //   await cookieManager.setCookie(
  //     url: WebUri.uri(Uri.parse(Constants.BaseURL)),
  //     name: "planId",
  //     value: _registerController.getPlanId,
  //     domain: Constants.BaseDomain,
  //     path: '/',
  //     expiresDate: expiresDate,
  //     isSecure: true,
  //   );
  //   await cookieManager.setCookie(
  //     url: WebUri.uri(Uri.parse(Constants.BaseURL)),
  //     name: "customerId",
  //     value: _registerController.getCustomerId,
  //     domain: Constants.BaseDomain,
  //     path: '/',
  //     expiresDate: expiresDate,
  //     isSecure: true,
  //   );
  // }

  @override
  void initState() {
    super.initState();
    //loadautoken();
    pullToRefreshController = PullToRefreshController(
      onRefresh: () async {
        if (Platform.isAndroid) {
          webViewController?.reload();
        } else if (Platform.isIOS) {
          webViewController?.loadUrl(
              urlRequest: URLRequest(url: await webViewController?.getUrl()));
        }
      },
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    //_registerController.createIndividual();
    // for remote web and app
    // var url = '${Constants.BaseURL}icr5/assets/assets/html/paymentICR.html';
    // for local web test
    var url = 'assets/html/paymentICR.html';

    return SafeArea(
        child: Column(children: <Widget>[
      Expanded(
        child: Stack(
          children: [
            InAppWebView(
              key: webViewKey,
              initialUrlRequest: URLRequest(
                  // for local web test
                  url: WebUri.uri(Uri.parse(url))),
              // for remote web and app
              // url: WebUri.uri(Uri.parse(
              //     "${Constants.BaseURL}icr5/assets/assets/html/payment.html"))),
              initialSettings: options,
              pullToRefreshController: pullToRefreshController,
              onWebViewCreated: (controller) {
                webViewController = controller;
              },
              onLoadStart: (controller, url) async {},
              onPermissionRequest: (controller, request) async {
                return PermissionResponse(
                    resources: request.resources,
                    action: PermissionResponseAction.GRANT);
              },
              shouldOverrideUrlLoading: (controller, navigationAction) async {
                var uri = navigationAction.request.url!;

                if (![
                  "http",
                  "https",
                  "file",
                  "chrome",
                  "data",
                  "javascript",
                  "about"
                ].contains(uri.scheme)) {
                  if (await canLaunchUrl(uri)) {
                    // Launch the App
                    await launchUrl(
                      uri,
                    );
                    // and cancel the request
                    return NavigationActionPolicy.CANCEL;
                  }
                }
                return NavigationActionPolicy.ALLOW;
              },
              onLoadStop: (controller, url) async {
                Log.debug('individual pay on load stop:');
                // List<Cookie> cookies = await cookieManager.getCookies(
                //     url: WebUri.uri(Uri.parse(Constants.BaseURL)));
                // // url: WebUri.uri(
                // //     Uri.parse('https://migration.ichinesereader.com/')));
                // cookies.forEach((cookie) {
                //   Log.debug('individual pay on load stop: ' +
                //       cookie.name +
                //       " " +
                //       cookie.value);
                // });
              },
              onReceivedError: (controller, request, error) {
                pullToRefreshController.endRefreshing();
              },
              onProgressChanged: (controller, progress) {
                if (progress == 100) {
                  pullToRefreshController.endRefreshing();
                }
                setState(() {
                  this.progress = progress / 100;
                  urlController.text = this.url;
                });
              },
              onUpdateVisitedHistory: (controller, url, androidIsReload) {
                setState(() {
                  this.url = url.toString();
                  urlController.text = this.url;
                });
              },
              onConsoleMessage: (controller, consoleMessage) {
                Log.debug(consoleMessage.message == 'done');
                Log.debug(widget.from == 'individual');
                var customerId = '';
                if (consoleMessage.message.indexOf('customerId') > -1 &&
                    widget.from == 'individual') {
                  customerId = consoleMessage.message.split(':')[1];
                  _registerController.createIndividual(customerId);
                  showGeneralDialog(
                      context: context,
                      transitionDuration: Duration(milliseconds: 400),
                      pageBuilder: (bc, ania, anis) {
                        return AccountSuccessDialog(
                            title: 'Creat Account Successfully'.tr,
                            message: 'Go to login page'.tr);
                      });
                }
              },
            ),
            progress < 1.0
                ? LinearProgressIndicator(value: progress)
                : Container(),
          ],
        ),
      ),
    ]));
  }
}
